package com.course.interceptor;
/*
@author By 林中小鸟
@package  com.self.introduction.config.inteceptor
@create 2021 - 10 - 2021\10\7 0007
@QQ: 357182695
@Em: themooncss@gmail.com
*/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.course.component.annotation.LoginToken;
import com.course.component.annotation.PassToken;
import com.course.component.util.HttpContextUtil;
import com.course.entity.User;
import com.course.masterservice.LoginTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginTokenService tokenService;
    @Resource
    RedisTemplate redisTemplate;
    private static final HashMap<String, Object> INFO;

    static {
        INFO = new HashMap<>();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //注释内容
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //默认全部检查
        else {
            if (method.isAnnotationPresent(LoginToken.class)) {
                LoginToken userLoginToken = method.getAnnotation(LoginToken.class);
                if (userLoginToken.required()) {
                    return true;
                }
            }
            String token = tokenService.getToken(request);
            // 执行认证
            if (StringUtils.isBlank(token)) {
                //这里其实是登录失效,没token了   这个错误也是我自定义的，读者需要自己修改
                //throw new RuntimeException("无token，请重新登录");
                setReturn(response,500,"无效Token，请重新登录",INFO);
                return false;
            }

            //获取用户信息
            User loginUser = tokenService.getLoginUser(token);
            if(loginUser == null){
                setReturn(response,500,"无效Token，请重新登录",INFO);
                return false;
            }
            request.setAttribute("LOGINUSER", loginUser);
            //todo 设置登录信息 线程隔离
            //ThreadLocal 使用完要移除
            //CurrentUserUtil.setRequestSource(requestSource);
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //ThreadLocal 使用完要移除
        //CurrentUserUtil.remove();
    }

    //返回错误信息
    private static void setReturn(HttpServletResponse response, int status, String msg, Map<String,Object> data) throws IOException {
        ((HttpServletResponse) response).setHeader("Access-Control-Allow-Credentials", "true");
        ((HttpServletResponse) response).setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        //UTF-8编码
        ((HttpServletResponse) response).setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        JSONObject json = new JSONObject();
        json.put("code", status);
        json.put("message", msg);
        json.put("data", data);
        String res = JSON.toJSONString(json);
        ((HttpServletResponse) response).getWriter().print(res);
    }
}
